package cz.movie.subRenamerGUI;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class RedirecterToJTextArea {
	// private JTextArea textArea;
	private JTextPane textArea;

	public RedirecterToJTextArea(JTextPane textArea) {
		super();
		this.textArea = textArea;
		textArea.setEditable(false);
		redirectSystemStreams();
	}

	private void updateTextArea(final String text) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				textArea.setEditable(true);
				if (text.startsWith("ERROR")) {
					append(Color.RED, text);
				} else {
					append(Color.BLACK, text);
				}
				textArea.setEditable(false);
			}
		});
	}

	public void append(Color c, String s) { // better implementation--uses
		// StyleContext
		StyleContext sc = StyleContext.getDefaultStyleContext();
		AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

		int len = textArea.getDocument().getLength(); // same value as
		// getText().length();
		textArea.setCaretPosition(len); // place caret at the end (with no selection)
		textArea.setCharacterAttributes(aset, false);
		textArea.replaceSelection(s); // there is no selection, so inserts at caret
	}

	private void redirectSystemStreams() {
		OutputStream out = new OutputStream() {
			@Override
			public void write(int b) throws IOException {
				updateTextArea(String.valueOf((char) b));
			}

			@Override
			public void write(byte[] b, int off, int len) throws IOException {
				updateTextArea(new String(b, off, len));
			}

			@Override
			public void write(byte[] b) throws IOException {
				write(b, 0, b.length);
			}
		};
		PrintStream outPrint = new PrintStream(out);
		System.setOut(outPrint);
		System.setErr(outPrint);
	}
}
